<template>
  <div class="medicine-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>药品信息查询</h2>
          <el-input
            v-model="searchQuery"
            placeholder="请输入药品名称"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
      </template>

      <el-table :data="medicineList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="medicineName" label="药品名称"></el-table-column>
        <el-table-column prop="description" label="药品描述"></el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              :type="scope.row.inCart ? 'success' : 'primary'"
              size="small"
              :disabled="scope.row.inCart"
              @click="addToCart(scope.row)"
            >
              {{ scope.row.inCart ? '已加入购物车' : '加入购物车' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listMedicine } from '@/api/medicine'
import { listStock } from '@/api/stock'
import { listItem, addItem } from '@/api/item'

// 搜索关键词
const searchQuery = ref('')

// 药品列表
const medicineList = ref([])

// 购物车商品ID列表
const cartItems = ref([])

// 获取购物车商品列表
const getCartItems = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const res = await listItem({ userId: userInfo.id })
    cartItems.value = res.data.map((item) => item.medicineId)
  } catch (error) {
    console.error('获取购物车列表失败', error)
  }
}

// 获取药品列表和库存信息
const getMedicineList = async () => {
  try {
    // 获取药品列表
    const medicineRes = await listMedicine({
      medicineName: searchQuery.value,
    })

    // 获取库存列表
    const stockRes = await listStock()

    // 将库存信息和购物车状态合并到药品信息中
    medicineList.value = medicineRes.data.map((medicine) => {
      const stock = stockRes.data.find((s) => s.medicineId === medicine.id)
      return {
        ...medicine,
        stock: stock ? stock.quantity : 0,
        inCart: cartItems.value.includes(medicine.id),
      }
    })
  } catch (error) {
    console.error('获取药品列表失败', error)
  }
}

// 搜索
const handleSearch = () => {
  getMedicineList()
}

// 加入购物车
const addToCart = async (medicine) => {
  if (medicine.stock <= 0) {
    ElMessage.warning('该药品库存不足')
    return
  }

  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    await addItem({
      userId: userInfo.id,
      medicineId: medicine.id,
      quantity: 1,
    })

    // 刷新购物车状态
    await getCartItems()
    await getMedicineList()
  } catch (error) {
    console.error('加入购物车失败', error)
    ElMessage.error('加入购物车失败')
  }
}

// 初始化
onMounted(async () => {
  await getCartItems()
  await getMedicineList()
})
</script>
